﻿/*****************************************************
*File Name: Utils.cs								
*Writer: 周燕龙
*Ver:1.0
*Created Date: 2009-06-18						
*Description: 工具类,常用方法
												
*****************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;

namespace Hisuntech.SystemFramework.Web
{
    public class Utils
    {
        /// <summary>
        /// 判断 是否为GUID类型 32位
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        public static bool IsGuid(string strInput)
        {
            if (!string.IsNullOrEmpty(strInput))
                return System.Text.RegularExpressions.Regex.IsMatch(strInput, @"^[A-Fa-f0-9]{8}(-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            else
                return false;
        }

        /// <summary>
        /// 防SQL注入
        /// </summary>
        /// <param name="strInput">字符串</param>
        /// <returns></returns>
        public static bool GetSafeStr(string strInput)
        {
            if (!string.IsNullOrEmpty(strInput))
            {
                strInput = System.Text.RegularExpressions.Regex.Replace(strInput, "'", "''");
                string sqlRule = @"(from)|(convert)|(select )|(insert )|(delete from)|(count\()|(drop table)|(update )|(xp_cmdshell)|(exec master)|(net localgroup administrators)|(delete from)|(net user)|( or)|(asc\()|(mid\()|(char\()|(truncate )";
                return System.Text.RegularExpressions.Regex.IsMatch(strInput, sqlRule, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            }
            return false;
        }


        /// <summary>
        /// 检测是否符合email格式
        /// </summary>
        /// <param name="strEmail">要判断的email字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsValidEmail(string strEmail)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        /// <summary>
        /// 检测是否为整数
        /// </summary>
        /// <param name="strInt"></param>
        /// <returns></returns>
        public static bool IsInteger(string strInt)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(strInt, @"^\d*$");
        }

        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");

        }


        /// <summary>
        /// 是否是手机号
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsTelephone(string str)
        {
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^(1)\d{10}$"); //new System.Text.RegularExpressions.Regex(@"^(?:13\d|15[0189])-?\d{5}(\d{3}|\*{3})$");
            return reg1.IsMatch(str);
        }

        /// <summary>
        /// 返回 HTML 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string HtmlEncode(string str)
        {
            return System.Web.HttpUtility.HtmlEncode(str);
        }

        /// <summary>
        /// 返回 HTML 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string HtmlDecode(string str)
        {
            return System.Web.HttpUtility.HtmlDecode(str);
        }

        /// <summary>
        /// 产生简单随即字符串
        /// </summary>
        /// <param name="p_ilength"></param>
        /// <returns></returns>
        public static string RandomString(int p_ilength)
        {
            string str = "";
            string[] strgroup = new string[36] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "g", "k", "l", "m", "n", "o", "p", "k", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
            Random r = new Random();
            for (int i = 0; i < p_ilength; i++)
            {
                str += strgroup[r.Next(36)];
            }
            return str;
        }

        #region 可逆加密

        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string EncryptDES(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = Encoding.UTF8.GetBytes(encryptKey);
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();

                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string EncryptDESGB(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.GetEncoding("GB2312").GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = Encoding.GetEncoding("GB2312").GetBytes(encryptKey);
                byte[] inputByteArray = Encoding.GetEncoding("GB2312").GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();

                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }
        /// <summary>
        /// DES加密字符串 ///zyl
        /// </summary>
        public static string EncryptDES(string encryptString)
        {
            return EncryptDES(encryptString, "Hisuntech");
        }
        /// <summary>
        /// DES加密字符串
        /// </summary>
        public static string EncryptDESGB(string encryptString)
        {
            return EncryptDESGB(encryptString, "richtext");
        }
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string DecryptDESGB(string decryptString, string decryptKey)
        {
            try
            {

                byte[] rgbKey = Encoding.GetEncoding("GB2312").GetBytes(decryptKey);
                byte[] rgbIV = Encoding.GetEncoding("GB2312").GetBytes(decryptKey);
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();

                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.GetEncoding("GB2312").GetString(mStream.ToArray());
            }
            catch (System.Exception e)
            {
                return decryptString;
            }
        }
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string DecryptDES(string decryptString, string decryptKey)
        {
            try
            {

                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = Encoding.UTF8.GetBytes(decryptKey);
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();

                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch (System.Exception e)
            {
                return decryptString;
            }
        }
        /// <summary>
        /// DES解密字符串
        /// </summary>
        public static string DecryptDES(string decryptString)
        {
            return DecryptDES(decryptString, "richtext");
        }
        /// <summary>
        /// DES解密字符串
        /// </summary>
        public static string DecryptDESGB(string decryptString)
        {
            return DecryptDESGB(decryptString, "richtext");
        }


        #endregion

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="str">内容</param>
        /// <param name="p_strurl">目录</param>
        /// <returns></returns>
        public static bool WriteFile(string str, string p_strurl)
        {

            Encoding code = Encoding.GetEncoding("utf-8");
            string url = HttpContext.Current.Server.MapPath(p_strurl);
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(url, true, code);
                sw.WriteLine(str);
                sw.Flush();
            }
            catch (System.Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
                HttpContext.Current.Response.End();
            }
            finally
            {
                sw.Close();
            }
            return true;

        }



        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="Strings">文件内容</param>
        public static void WriteErrFile(string Path, string Strings)
        {
            if (!System.IO.File.Exists(Path))
            {
                System.IO.FileStream f = System.IO.File.Create(Path);
                f.Close();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.GetEncoding("gb2312"));
            f2.WriteLine(Strings);
            f2.Close();
            f2.Dispose();
        }





        /// <summary>
        /// 返回字符的真实长度
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int TrueLen(string str)
        {
            System.Text.ASCIIEncoding n = new System.Text.ASCIIEncoding();
            byte[] b = n.GetBytes(str);
            int val = 0;
            for (int i = 0; i <= b.Length - 1; i++)
            {
                if (b[i] == 63)
                {
                    val++;
                }
                val++;
            }
            return val;

        }


        ///   <summary>   
        ///   取出文本中的图片地址,返回一个数组   
        ///   </summary>   
        ///   <param   name="HTMLStr">HTMLStr</param>   
        public static string[] GetImgUrl(string HTMLStr)
        {
            string str = string.Empty;
            Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>", RegexOptions.Compiled);
            MatchCollection _m = r.Matches(HTMLStr.ToLower());
            for (int i = 0; i < _m.Count; i++)
            {
                if (_m[i].Success)
                    str += _m[i].Result("${url}") + "$";
            }
            char[] split = { '$' };
            string[] refString = str.TrimEnd('$').Split(split);
            return refString;

        }

        public static string GetSubString(string val, int len)
        {
            if (string.IsNullOrEmpty(val))
                return "&nbsp;";
            else
            {
                if (val.Length > len)
                    return val.Substring(0, len) + "…";
                else
                    return val;
            }

        }



    }
}
